package middleware

import (
	"OJCenter/global"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

// PriHandler 拦截器
func PriHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var data interface{}
		claims, _ := c.Get("claims")
		// 获取请求的URI
		uri := c.Request.URL.RequestURI()
		// 获取请求方法
		cmd := c.Request.Method
		// 判断策略中是否存在
		var uriRaw string
		switch claims {
		default:
			switch cmd {
			case "GET":
				uriRaw = global.Conf.PPolicy.RegularUser.Get
			case "POST":
				uriRaw = global.Conf.PPolicy.RegularUser.Post
			}
		case 2:
			switch cmd {
			case "GET":
				uriRaw = global.Conf.PPolicy.Admin.Get
			case "POST":
				uriRaw = global.Conf.PPolicy.Admin.Post
			}
		case 3:
			switch cmd {
			case "GET":
				uriRaw = global.Conf.PPolicy.SuperAdmin.Get
			case "POST":
				uriRaw = global.Conf.PPolicy.SuperAdmin.Post
			}
		}

		uris := strings.Split(";", uriRaw)
		flag := false
		for _, _uri := range uris {
			if uri == _uri {
				flag = true
				break
			}
		}
		if flag {
			c.Next()
			return
		}

		c.JSON(http.StatusUnauthorized, gin.H{
			"code": global.ERROR_AUTH_CHECK_TOKEN_FAIL,
			"msg":  global.GetMsg(global.ERROR_AUTH_CHECK_TOKEN_FAIL),
			"data": data,
		})
		c.Abort()
		return
	}
}
